package cc.ufinity.networkdiagnose.widget;

import java.util.ArrayList;
import java.util.Map;

import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.Task.PingTask;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.util.StringUtils.PING_RESULT;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class PingWidget extends GeneralTestWidget {

    private ScrollView pingSv;
    private LinearLayout pingRsLayout;
    private Activity ctx;
    private Handler handler;
    private Button backBtn;
    private Button startBtn;
    private Button btnRetest;
    private NetworkManager nm;
    private EditText et;
    private Task task;
    private String fileName;

    public PingWidget(Activity context) {
        super(context);
        inflate(context, R.layout.ping, this);
        this.ctx = context;
        pingSv = (ScrollView) this.findViewById(R.id.ping_test_ScrView);
        pingRsLayout = (LinearLayout) this.findViewById(R.id.pint_test_detail);
        backBtn = (Button) this.findViewById(R.id.ping_test_btnback);
        startBtn = (Button) this.findViewById(R.id.btn_ping_start);
        btnRetest = (Button) findViewById(R.id.btn_ping_retest);
        et = (EditText) this.findViewById(R.id.pingEditText);
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.PING_SUCCESS:
                    update();
                    break;
                case MessageWhat.PING_FAILED:
                    showMessage(ctx, "PING测试失败，请返回重试！");
                    dismissMessageDialog();
                    break;
                case MessageWhat.NETWORK_INVALID:
                    dismissMessageDialog();
                    showMessage(ctx, "无法连接至因特网.");
                    break;
                case MessageWhat.FTP_ACCOUNT_INVALID:
                    dismissMessageDialog();
                    showMessage(ctx, "无法获取FTP账号，请检查FTP配置.");
                    break;
                case MessageWhat.FTP_UPLOAD_TASK_DONE:
                    dismissMessageDialog();
                    showMessage(ctx, "上传成功.");
                    break;
                case MessageWhat.FTP_UPLOAD_FAILED:
                    dismissMessageDialog();
                    showMessage(ctx, "上传失败，请检查FTP配置是否正确.");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                    dismissMessageDialog();
                    showMessage(ctx, "FTP登录失败，请检查FTP配置是否正确.");
                    break;
                }
            }
        };
        btnRetest.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != fileName) {
                    new UploadResultTask().execute();
                } else {
                    showMessage(ctx, "文件已上传或未进行PING测试.");
                }
            }
        });
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                back(ctx);
            }
        });
        startBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startPing();
            }
        });
        task = new Task();
    }

    public void update() {
        TextView tv = new TextView(ctx);
        tv.setTextSize(12);
        tv.setText(nm.getPingResult());
        pingRsLayout.addView(tv);
        setScrollViewDown(pingSv);
        
        
        task.testCount = 10;
        PingTask pingTask = task.newPingTask("");
        Map<String, String> res = StringUtils.pingResult(nm.getPingResult());
        pingTask.bytes = res.get(PING_RESULT.PING_RESULT_BYTE_NO);
        pingTask.time = res.get(PING_RESULT.PING_RESULT_TIME);
        pingTask.ttl = res.get(PING_RESULT.PING_RESULT_TTL);
        ArrayList<PingTask> tasks = new ArrayList<PingTask>(1);
        tasks.add(pingTask);
        task.pingTasks = tasks;
        task.endTime = StringUtils.getDateTime();
        this.dismissMessageDialog();
        new UploadResultTask().execute();
    }

    public void startPing() {
        final String addr = et.getText().toString();
        if (StringUtils.isEmpty(addr)) {
            this.showMessage(ctx, "请输入地址或IP.");
            return;
        }

        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp != null) {
            this.showMessageDialog(ctx, "正在进行Ping测试...");
            int type = NetworkManager.detectNetworkConnectivity(ctx);
            if (type == -1) {
                sendMsg(MessageWhat.NETWORK_INVALID, handler);
            } else {
                initTask(task, ctx, type);
                nm = new NetworkManager();
                nm.setHandler(handler);
                new Thread() {
                    public void run() {
                        task.startTime = StringUtils.getDateTime();
                        nm.ping(addr, 10, 64);
                    }
                }.start();
            }
        }
    }
    private class UploadResultTask extends AsyncTask<Void, Void, String> {
        protected void onPreExecute() {
            showMessage(ctx, "正在上传结果...");
        }

        @Override
        protected String doInBackground(Void... params) {
            
            if (fileName == null) {
                TaskParser parser = new PullTaskParser();
                fileName = parser.XmlFileCreator(task);
            }
            if (uplod(fileName, ctx, handler)) {
                fileName = null;
            }
            return fileName;
        }
        /*
        protected void onPostExecute(String result) {
            if (result == null) {
                showMessage(ctx, "上传成功.");
            }
        }*/
    }
}
